# -*- coding:UTF-8 -*-
import sublime, sublime_plugin
import time
import os
import re
import codecs

try:
    import helper
except ImportError:
    from . import helper


VIEW_ITEM_DICT = {}
ALL_ITEM_DICT  = {}
TEMP_PATH      = ""

def init():
	global TEMP_PATH
	TEMP_PATH = sublime.packages_path()+"/User/GoMark.cache"

#显示跳转列表
class GotoMarkCommand(sublime_plugin.WindowCommand):
    def run(self):
		global VIEW_ITEM_DICT
		itemList = VIEW_ITEM_DICT.keys()
		self.window.show_quick_panel(itemList, self.on_done)
		pass

    def on_done(self, index):
		try:
			global VIEW_ITEM_DICT
			itemList = VIEW_ITEM_DICT.keys()
			text = itemList[index]
			line = VIEW_ITEM_DICT[text]
			if self.window.active_view():
				self.window.active_view().run_command("goto_line", {"line": line} )

		except ValueError:
			pass

#划分
def parseFile(filename, TEMP_PATH):
	print(filename)

	md5filename = helper.md5(filename)
	saveDir = os.path.join(TEMP_PATH, md5filename)
	helper.deleteFiles(saveDir,saveDir)
    
	if not os.path.exists(saveDir):
		os.makedirs(saveDir)

	outputpath = os.path.join(saveDir,"file.mark")

	fin = codecs.open(filename,"r","utf-8")
	lineNum = 0
	itemList = {}

	for line in fin: 
		lineNum = lineNum + 1
		match = re.match(".*pragma mark (.*)\n*", line)    
		if match:
			text = match.group(1)
			itemList[text] = lineNum

	fin.close()
	
	global ALL_ITEM_DICT
	global VIEW_ITEM_DICT
	ALL_ITEM_DICT[filename] = itemList
	VIEW_ITEM_DICT = itemList
	
	helper.writeFile(outputpath, str(itemList))

class MarkListener(sublime_plugin.EventListener):
	def __init__(self):
		self.lastTime = 0

	def on_post_save(self, view):
		filename = view.file_name()
		if not filename:
			return
		curTime = time.time()
		if curTime - self.lastTime < 2:
			return
		self.lastTime = curTime
		global TEMP_PATH
		try:
			parseFile(filename, TEMP_PATH)
		except ValueError:
			pass

	def on_activated(self, view):
		filename = view.file_name()
		print("on_activated:", filename)

		global ALL_ITEM_DICT
		global VIEW_ITEM_DICT
		md5filename = helper.md5(filename)
		saveDir = os.path.join(TEMP_PATH, md5filename)
		outputpath = os.path.join(saveDir,"file.mark")
		if filename in ALL_ITEM_DICT:
			VIEW_ITEM_DICT = ALL_ITEM_DICT[filename]
		elif os.path.exists(outputpath):
			text = helper.readFile(outputpath)
			VIEW_ITEM_DICT = eval(text)
			ALL_ITEM_DICT[filename] = VIEW_ITEM_DICT
		else:
			VIEW_ITEM_DICT = {}

# st3
def plugin_loaded():
    sublime.set_timeout(init, 200)

# st2
if not helper.isST3():
    init()
